package com.gxcommunication.sociallearn.utils;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 
 * 字符串操作工具包
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class StringUtils 
{
	private final static Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	//private final static SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	//private final static SimpleDateFormat dateFormater2 = new SimpleDateFormat("yyyy-MM-dd");
	
	private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
	};

	private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};
	
	/**
	 * 将字符串转位日期类型
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate) {
		try {
			return dateFormater.get().parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}
	
	/**
	 * 以友好的方式显示时间
	 * @param sdate
	 * @return
	 */
	public static String friendly_time(String sdate) {
		Date time = toDate(sdate);
		if(time == null) {
			return "Unknown";
		}
		String ftime = "";
		Calendar cal = Calendar.getInstance();
		
		//判断是否是同�?��
		String curDate = dateFormater2.get().format(cal.getTime());
		String paramDate = dateFormater2.get().format(time);
		if(curDate.equals(paramDate)){
			int hour = (int)((cal.getTimeInMillis() - time.getTime())/3600000);
			if(hour == 0)
				ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000,1)+"分钟";
			else 
				ftime = hour+"小时";
			return ftime;
		}
		
		long lt = time.getTime()/86400000;
		long ct = cal.getTimeInMillis()/86400000;
		int days = (int)(ct - lt);		
		if(days == 0){
			int hour = (int)((cal.getTimeInMillis() - time.getTime())/3600000);
			if(hour == 0)
				ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000,1)+"分钟";
			else 
				ftime = hour+"小时";
		}
		else if(days == 1){
			ftime = "昨天";
		}
		else if(days == 2){
			ftime = "前天";
		}
		else if(days > 2 && days <= 10){ 
			ftime = days+"天前";			
		}
		else if(days > 10){			
			ftime = dateFormater2.get().format(time);
		}
		return ftime;
	}
	
	/**
	 * 判断给定字符串时间是否为今日
	 * @param sdate
	 * @return boolean
	 */
	public static boolean isToday(String sdate){
		boolean b = false;
		Date time = toDate(sdate);
		Date today = new Date();
		if(time != null){
			String nowDate = dateFormater2.get().format(today);
			String timeDate = dateFormater2.get().format(time);
			if(nowDate.equals(timeDate)){
				b = true;
			}
		}
		return b;
	}
	
	/**
	 * 判断给定字符串是否空白串�?
	 * 空白串是指由空格、制表符、回车符、换行符组成的字符串
	 * 若输入字符串为null或空字符串，返回true
	 * @param input
	 * @return boolean
	 */
	public static boolean isEmpty( String input ) 
	{
		if ( input == null || "".equals( input ) )
			return true;
		
		for ( int i = 0; i < input.length(); i++ ) 
		{
			char c = input.charAt( i );
			if ( c != ' ' && c != '\t' && c != '\r' && c != '\n' )
			{
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是不是一个合法的电子邮件地址
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email){
		if(email == null || email.trim().length()==0) 
			return false;
	    return emailer.matcher(email).matches();
	}
	/**
	 * 字符串转整数
	 * @param str
	 * @param defValue
	 * @return
	 */
	public static int toInt(String str, int defValue) {
		try{
			return Integer.parseInt(str);
		}catch(Exception e){}
		return defValue;
	}
	/**
	 * 对象转整�?
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static int toInt(Object obj) {
		if(obj==null) return 0;
		return toInt(obj.toString(),0);
	}
	/**
	 * 对象转整�?
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static long toLong(String obj) {
		try{
			return Long.parseLong(obj);
		}catch(Exception e){}
		return 0;
	}
	/**
	 * 字符串转布尔�?
	 * @param b
	 * @return 转换异常返回 false
	 */
	public static boolean toBool(String b) {
		try{
			return Boolean.parseBoolean(b);
		}catch(Exception e){}
		return false;
	}
	
	/**
	 * //中文字符串编码转换
	 * @paramurl
	 * @return 返回转换后的字符串
	 */
	public static String URLEncoderChange(String text){
		if (text == null || text.isEmpty()) return "";
		String tempString = "";
		try {
			tempString =URLEncoder.encode(text, "UTF-8");
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tempString;
	}
	/**
	 * 判断字符是不是{或者[
	 * @param json
	 * @return
	 */
	public static boolean isGetJsonArray(String json){
		String temp = "[";
		if (json.indexOf(temp) == -1) 
		{
			return false;
		}else {
			return true;
		}		
	}

	/**
	 * List 等数据转换成String
	 * @param data
	 * @return
	 */
	public static String valueofObject(Object data){
		Gson gson = new Gson();
		return gson.toJson(data);
	}

	public static String doubleToStringDeleteZero(double value) {
		String val = String.valueOf(value);
		return stringToStringDeleteZero(val);
	}

	/**
	 * 字符串转字符串去掉小数点后面的0
	 *
	 * @param value
	 * @return
	 */
	public static String stringToStringDeleteZero(String value) {
		String val = String.valueOf(value).trim();
		if (TextUtils.isEmpty(val)) {
			return "";
		}
		if (val.indexOf(".") > 0) {
			val = val.replaceAll("0+?$", "");//去掉多余的0
			val = val.replaceAll("[.]$", "");//如最后一位是.则去掉
		}
		return val;
	}

	/**
	 * string 转换万  个   单位表示
	 *
	 * @param value
	 * @return
	 */
	public static String stringToStringUnit(String value) {
		return intToStringUnit(Integer.valueOf(value));
	}

	/**
	 * int 转换万  个   单位表示
	 *
	 * @param value
	 * @return
	 */
	public static String intToStringUnit(int value) {
		String s = String.valueOf(value);
		String sVal = s.contains(".") ? s.split("\\.")[0] : s;

		value = Integer.valueOf(sVal);
		if (value >= 10000 && value < 100000000) {
			String val = String.valueOf(value);

			String s1 = val.substring(0, val.length() - 4) + "." + val.substring(val.length() - 4, val.length() - 2);
			String s2 = new BigDecimal(s1).setScale(1, BigDecimal.ROUND_HALF_UP).toString();
			return stringToStringDeleteZero(s2) + "万";
		} else if (value >= 100000000) {
			String val = String.valueOf(value);
			String s1 = val.substring(0, val.length() - 8) + val.substring(val.length() - 8, val.length() - 7);
			String s2 = new BigDecimal(s1).setScale(1, BigDecimal.ROUND_HALF_UP).toString();
			return stringToStringDeleteZero(s2) + "亿";
		}
		return value + "";
	}

	public static boolean vertifyPhone(Context context,String phone) {
		if (TextUtils.isEmpty(phone)) {
			ToastUtils.showShort(context,"手机号不能为空!");
			return false;
		}
		if (phone.length() == 11 && phone.startsWith("1")) {
			return true;
		}
		ToastUtils.showShort(context,"请确认手机号格式!");
		return false;
	}

	/**
	 * Get MD5 Code
	 */
	public static String getMD5(String text) {
		try {
			byte[] byteArray = text.getBytes("utf8");
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(byteArray, 0, byteArray.length);
			return convertToHex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * Convert byte array to Hex string
	 */
	private static String convertToHex(byte[] data) {
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

	public static String getUrlString(String url, String key) {
		String rex = "[?&]" + key + "=([^&]*)";
		Pattern pattern = Pattern.compile(rex);// 匹配的模式
		Matcher m = pattern.matcher("&" + url);
		while (m.find()) {
			return m.group(1);
		}
		return "";
	}

	public static boolean isTbaoOrTianMaoRex(String url){
//		String rex = "http[s]?://.*?(?:\\.((?:taobao)|(?:tmall)|(?:liangxinyao)|(?:95095)))\\.";
		String rex = "http[s]?://.*?(\\.(taobao)|(tmall)|(liangxinyao)\\.)";
		Pattern pattern = Pattern.compile(rex);
//		return Pattern.matches(rex, url);
		return pattern.matcher(url).find();
	}

	public static boolean isProductInfoRex(String url){
//		String rex = "http[s]?://.*?(?:\\.(?:(?:taobao)|(?:tmall)|(?:liangxinyao)|(?:95095)))\\..*?(?:(?:[?|&]id=(\\d*)(?!.*?[\\?|&]item_id=))|(?:[?|&]item_id=(\\d*)))";
		String rex = "http[s]?://.*?(\\.(?:(taobao)|(tmall)|(liangxinyao)|(95095)))\\..*?(?:(?:[?|&]id=(\\d*)(?!.*?[\\?|&]item_id=))|(?:[?|&]item_id=(\\d*)))";
		Pattern pattern = Pattern.compile(rex);
		return pattern.matcher(url).find();

	}

	public static String getProductId(String url){
//		String rex = "(?:&|\\?)(?:(?:itemId)|(?:id))=^(\\d*)";
		String rex = "&?(itemId|id)=(\\d*)";
		Pattern pattern = Pattern.compile(rex);
		Matcher m = pattern.matcher(url);
		String id = "";
		while (m.find()){
			id =  m.group(2);
		}
		LogHelper.e(id);
		return id;
	}


	/**
	 * 首行缩进的SpannableString
	 *
	 * @param length      首行缩进宽度 dp
	 * @param description 描述信息
	 */
//	public static SpannableString getSpannableString(float length, String description) {
//		if (description == null || description.isEmpty()){
//			return  new SpannableString("");
//		}
//		SpannableString spannableString = new SpannableString(description);
//		int marginSpanSize = SizeUtils.dp2px(length);
//		LeadingMarginSpan leadingMarginSpan = new LeadingMarginSpan.Standard(marginSpanSize, 0);//仅首行缩进
//		spannableString.setSpan(leadingMarginSpan, 0, description.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//		return spannableString;
//	}
}
